package com.smartlazy.sequence.server.config;

import com.smartlazy.sequence.core.sequence.BaseRangeSequence;
import com.smartlazy.sequence.core.sequence.Sequence;
import com.smartlazy.sequence.mysql.core.mysql.MysqlSeqRangeMgr;
import com.smartlazy.sequence.mysql.core.sequence.MysqlRangeSequence;
import com.smartlazy.sequence.redis.core.redis.RedisSeqRangeMgr;
import com.smartlazy.sequence.redis.core.sequence.RedisRangeSequence;
import com.smartlazy.sequence.redis.core.sequence.RedisSequence;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;

/**
 * @author howe
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(SequenceProperties.class)
@AutoConfigureBefore(MybatisPlusConfig.class)
public class SequenceAutoConfig {

    @Autowired
    private SequenceProperties sequenceProperties;

    @Resource
    private RedisTemplate<String, Long> redisTemplate;

    /**
     * 注入Sequence
     */
    @Bean
    public Sequence nextMerchantId(){
        RedisSeqRangeMgr range = new RedisSeqRangeMgr();
        range.setRedisTemplate(redisTemplate);
        range.setStep(sequenceProperties.getStep());
        BaseRangeSequence sequence = new BaseRangeSequence();
        sequence.setName("MerchantId");
        sequence.setSeqRangeMgr(range);
        return sequence;
    }

    /**
     * 注入DefaultSequence
     */
    @Bean
    public RedisSequence defaultSequence(){
        return new RedisSequence();
    }

    /**
     * 注入Sequence
     */
    @Bean
    public RedisRangeSequence nextAccId() {
        RedisSeqRangeMgr range = new RedisSeqRangeMgr();
        range.setRedisTemplate(redisTemplate);
        range.setStep(sequenceProperties.getStep());
        RedisRangeSequence sequence = new RedisRangeSequence();
        sequence.setSeqRangeMgr(range);
        return sequence;
    }

    /**
     * 注入Sequence
     */
    @Bean
    public MysqlRangeSequence nextMysqlId() {
        MysqlSeqRangeMgr range = new MysqlSeqRangeMgr();
        range.setStep(sequenceProperties.getStep());
        range.setRetryTimes(sequenceProperties.getRetryTimes());
        MysqlRangeSequence sequence = new MysqlRangeSequence();
        sequence.setSeqRangeMgr(range);
        return sequence;
    }
}
